package com.ve.s2g.util

import java.io.File
import java.nio.file.Paths

object Shell {
    fun execute(command: String, workingDirectory: File = root.toFile(), environmentVariables: Map<String, String> = emptyMap()) {
        execute(command.split(" "), workingDirectory, environmentVariables)
    }

    fun execute(command: List<String>, workingDirectory: File = root.toFile(), environmentVariables: Map<String, String> = emptyMap()) {
        //Log.info("[${workingDirectory.name}] Executing: ${command.joinToString(" ")}")

        val processBuilder = ProcessBuilder(command)
            .directory(workingDirectory).inheritIO()

        processBuilder.environment().putAll(environmentVariables)
        processBuilder.start().waitFor()

        //Log.newline()
    }

    fun capture(command: String, workingDirectory: File = root.toFile()): String {
        return capture(command.split(" "),workingDirectory)
    }

    fun capture(command: List<String>, workingDirectory: File = root.toFile()): String {
        return ProcessBuilder(command)
            .directory(workingDirectory)
            .redirectOutput(ProcessBuilder.Redirect.PIPE)
            .redirectError(ProcessBuilder.Redirect.PIPE)
            .start().inputStream.bufferedReader(Charsets.UTF_8).readText()
    }
}

//object Paths {
//    fun root(): File = jarFile().parentFile.parentFile.parentFile.parentFile
//    fun configuration() = path("configuration")
//
//    fun producer() = path("producer")
//    fun producerContracts() = path("producer/contracts")
//    fun producerGen() = path("producer/src/gen/java")
//
//    fun streamProcessor() = path("stream-processor")
//    fun streamProcessorContracts() = path("stream-processor/contracts")
//    fun streamProcessorGen() = path("stream-processor/src/gen/java")
//
//    fun consumer() = path("consumer")
//    fun consumerContracts() = path("consumer/contracts")
//    fun consumerGen() = path("consumer/src/gen/java")
//
//    fun acceptanceTests() = path("acceptance-tests")
//
//    private fun path(path: String) = File(root(), path)
//    private fun jarFile() = File(this::class.java.protectionDomain.codeSource.location.toURI().path)
//}

fun main(args: Array<String>) {
    val shellfile = getPathInCP("cmd/test.bat")

    //println(shellfile)
    println(Shell.capture("cmd.exe /c ${shellfile}"))
}